import { ref } from 'vue';

export const setupWindowInteractions = (
    chatWindowRef,
    isMinimized,
    isMaximized,
    isPinned,
    rightPosition,
    bottomPosition,
    windowWidth,
    windowHeight,
    inputMessage,
    chatMessages,
    apiStore,
    errorMessage,
    initialWidth,
    initialHeight,
    initialRight,
    initialBottom
) => {
    let startX = 0;
    let startY = 0;
    let offsetX = 0;
    let offsetY = 0;

    const onHeaderMouseDown = (e) => {
        if (!isPinned.value) {
            e.preventDefault();
            startX = e.clientX;
            startY = e.clientY;
            offsetX = rightPosition.value;
            offsetY = bottomPosition.value;
            document.addEventListener('mousemove', onMouseMove);
            document.addEventListener('mouseup', onMouseUp);
        }
    };

    const onMouseMove = (e) => {
        const dx = e.clientX - startX;
        const dy = e.clientY - startY;
        let newRight = offsetX - dx;
        let newBottom = offsetY - dy;

        const maxRight = window.innerWidth - windowWidth.value;
        const maxBottom = window.innerHeight - windowHeight.value;

        newRight = Math.max(0, Math.min(newRight, maxRight));
        newBottom = Math.max(0, Math.min(newBottom, maxBottom));

        rightPosition.value = newRight;
        bottomPosition.value = newBottom;
    };

    const onMouseUp = () => {
        document.removeEventListener('mousemove', onMouseMove);
        document.removeEventListener('mouseup', onMouseUp);
    };

    const toggleMinimize = () => {
        if (isMinimized.value) {
            // 还原窗口
            windowWidth.value = initialWidth;
            windowHeight.value = initialHeight;
            rightPosition.value = initialRight;
            bottomPosition.value = initialBottom;
        } else {
            // 记录当前宽度，最小化时宽度保持初始值
            if (chatWindowRef.value) {
                const headerHeight = chatWindowRef.value.querySelector('.chat-header')?.offsetHeight;
                if (headerHeight) {
                    windowWidth.value = initialWidth;
                    windowHeight.value = headerHeight;
                    rightPosition.value = 20;
                    bottomPosition.value = 20;
                }
            }
        }
        isMinimized.value = !isMinimized.value;
    };

    const toggleMaximize = () => {
        if (isMaximized.value) {
            // 恢复到初始大小和位置
            windowWidth.value = initialWidth;
            windowHeight.value = initialHeight;
            rightPosition.value = initialRight;
            bottomPosition.value = initialBottom;
        } else {
            // 最大化窗口
            rightPosition.value = 0;
            bottomPosition.value = 0;
            windowWidth.value = window.innerWidth;
            windowHeight.value = window.innerHeight;
        }
        isMaximized.value = !isMaximized.value;
        isMinimized.value = false;
    };

    const closeChatWindow = () => {
        isMinimized.value = false;
        isMaximized.value = false;
        // 恢复到初始大小和位置
        windowWidth.value = initialWidth;
        windowHeight.value = initialHeight;
        rightPosition.value = initialRight;
        bottomPosition.value = initialBottom;
    };

    let resizeStartX = 0;
    let resizeStartY = 0;
    let initialResizeRight = 0;
    let initialResizeBottom = 0;
    let initialResizeWidth = 0;
    let initialResizeHeight = 0;

    const startResize = (e) => {
        if (!isPinned.value) {
            resizeStartX = e.clientX;
            resizeStartY = e.clientY;
            initialResizeRight = rightPosition.value;
            initialResizeBottom = bottomPosition.value;
            initialResizeWidth = windowWidth.value;
            initialResizeHeight = windowHeight.value;
            document.addEventListener('mousemove', resizeWindow);
            document.addEventListener('mouseup', endResize);
        }
    };

    const resizeWindow = (e) => {
        const dx = e.clientX - resizeStartX;
        const dy = e.clientY - resizeStartY;

        const minWidth = 400;
        const minHeight = 200;

        const newWidth = Math.max(minWidth, initialResizeWidth + dx);
        const newHeight = Math.max(minHeight, initialResizeHeight + dy);

        const newRight = initialResizeRight - (newWidth - initialResizeWidth);
        const newBottom = initialResizeBottom - (newHeight - initialResizeHeight);

        rightPosition.value = newRight;
        bottomPosition.value = newBottom;
        windowWidth.value = newWidth;
        windowHeight.value = newHeight;
    };

    const endResize = () => {
        document.removeEventListener('mousemove', resizeWindow);
        document.removeEventListener('mouseup', endResize);
    };

    // 储存历史聊天记录的方法
    const sendChatHistoryMessage = async (message) => {
        const chatHistoryId = localStorage.getItem('chat_history_id');
        try {
            const response = await apiStore.sendChatHistoryMessage(message, chatHistoryId);
            if (response) {
                // 更新聊天记录ID
                localStorage.setItem('chat_history_id', response.chat_history_id);
            } else {
                console.error('聊天记录保存失败','error');
            }
        } catch (error) {
            console.error('聊天记录保存失败:', error);
        }
    };

    const sendMessage = async (message) => {
        if (message && message.content && message.content.trim()) {
            // 如果是第一次对话，则需要将设定词写入对话中
            if (chatMessages.value.length == 0) {
                chatMessages.value.push({
                    role: 'system',
                    content: apiStore.appKeyInfo.system_model
                });
            }
    
            // 添加用户消息到 chatMessages 数组
            chatMessages.value.push(message);
    
            try {
                // 定义一个变量，用于存储大模型的完整回复
                let fullResponse = '';
    
                const updateChat = (newResponsePart) => {
                    // 将新内容追加到完整回复中
                    fullResponse += newResponsePart;
    
                    // 更新最后一条消息的内容
                    const modelMessage = {
                        role: 'assistant',
                        content: fullResponse
                    };
    
                    // 如果最后一条消息不是用户消息，则更新它
                    if (chatMessages.value[chatMessages.value.length - 1].role !== "user") {
                        chatMessages.value[chatMessages.value.length - 1] = modelMessage;
                    } else {
                        // 否则，添加一条新消息
                        chatMessages.value.push(modelMessage);
                    }
                };
    
                // 发送聊天消息并接收 SSE 流式响应
                await apiStore.sendChatMessage(
                    {
                        model: apiStore.appKeyInfo.select_model,
                        messages: chatMessages.value
                    },
                    updateChat
                );
    
                // 发送聊天历史记录
                await sendChatHistoryMessage({
                    model: apiStore.appKeyInfo.select_model,
                    messages: chatMessages.value
                });
    
                errorMessage.value = '';
            } catch (error) {
                console.error('与大模型通信出错:', error);
                // 添加错误消息到 chatMessages 数组
                const errorMessageObj = {
                    role: 'assistant',
                    content: '与大模型通信出错，请稍后重试。'
                };
                chatMessages.value.push(errorMessageObj);
            }
            inputMessage.value = '';
        }
    };


    return {
        onHeaderMouseDown,
        toggleMinimize,
        toggleMaximize,
        closeChatWindow,
        startResize,
        resizeWindow,
        endResize,
        sendMessage
    };
};